<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script th:inline="javascript">
	var op = [[${op}]];
	var isTab = [(${isTab})];

	[# th:if="${op eq 'forRefresh'}"]
        async function refreshNestTableCtl[(${nestFieldName})](newIds, calcFields, rowCss) {
            var path = '[(${path})]';
            path = (path.indexOf("?")!=-1)? path += "&"+new Date().getTime() : path += "?"+new Date().getTime()

            var fieldName = '[(${nestFieldName})]';
            var strNewIds = "";
            if (newIds!=null) {
                strNewIds = newIds;
            }
			console.log('refreshNestTableCtl newIds', newIds);

			var isShowChk = true;
			var isNoShow = [(${isNoShow})] == 1;
			var dlt = 0;
			if (isShowChk) {
				dlt += 1;
			}
			if (isNoShow) {
				dlt += 1;
			}

            // 清除以前拉单所获取的值，否则反复再次拉单时会导致上次所拉的记录还存在
			$("[name^='cws_textarea_nest_field_']").remove();
			$("[name^='cws_span_nest_field_']").remove();

			showSpinning(true);

			var ajaxData = {
                newIds: strNewIds
            };
            ajaxGet(path, ajaxData).then((data) => {
                // console.log('data', data);
                console.log('fieldName', fieldName);
                console.log('toolbar', $('#toolbar_' + fieldName)[0]);
                $('#toolbar_' + fieldName).remove();

                // 自动拉单的时候，并不会在NestTableCtl中loadNestCtl，所以此时$("#nestTable_" + fieldName)可能未生成
                // $nestTableParent = $("#nestTable_" + fieldName).parent();
				$nestTableParent = $('#nestsheet_' + fieldName);

				// 清除之前已存在的嵌套表格
                $("#nestTable_" + fieldName).remove();

				if (isTab == 0) {
					// $("#nestTable_"+fieldName).html(data);
					$nestTableParent.append(data);
				} else {
					// 流程中选项卡式显示方式
					$("#tabs-[(${nestFormCode})]").html(data);
				}
				// console.log('data', data);
				console.log('calcFields');

				// 表格单元格间计算时，不启用计算控件
				if (!(calcFields && calcFields.length)) {
					initEventOfNestTable('nestTable_[(${nestFieldName})]', '[(${nestFieldName})]');
					callCalculateOnloadNestTable('nestTable_[(${nestFieldName})]', '[(${nestFieldName})]');
				}

                // 如果含有从模板中载入的计算单元格
                console.log('refreshNestTableCtl calcFields', calcFields);
                if (calcFields && calcFields.length) {
					$("#nestTable_" + fieldName).attr('hasCalcFields', 1);

					var aryCols = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
                	var num = 0;
                	$('#nestTable_[(${nestFieldName})]').find('tr').each(function() {
						$(this).find('input[name^=nest_field_]').each(function() {
							var $td = $(this).parent('td');
							var r = $td.parent().prevAll().length;
							var c = $td.prevAll().length;
							var cellName = aryCols[c-dlt] + (r+1);
							$(this).attr('cellRow', r+1);
							$(this).attr('cellCol', aryCols[c-dlt]);
						});

                		// 跳过表头和统计行
                		if (num == 0 || $(this).attr('id') == 'trStat') {
                			num++;
                			return;
						}
						for (var i in calcFields) {
							var json = calcFields[i];
							if (json.rowNum + 1 == num) {
								$(this).find('input[name^=nest_field_]').each(function() {
									console.log('input', $(this).attr('name'), $(this).attr('name').indexOf('_' + json.fieldName + '_'));
									if ($(this).attr('name').indexOf('_' + json.fieldName + '_')!=-1) {
										$(this).attr('calc', json.calc);
										$(this).attr('readonly', 'readonly');
									}
								});
							}
						}
						num ++;
					});

                	$('[name^=nest_field_]').change(function() {
						callCalc([[${nestFieldName}]], this);
					});
				}

				if (rowCss && rowCss.length > 0) {
					var num = 0;
					$('#nestTable_[(${nestFieldName})]').find('tr').each(function() {
						// 跳过表头
						if (num == 0) {
							num++;
							return;
						}
						for (var i in rowCss) {
							var json = rowCss[i];
							if (json.rowNum+1 == num) {
								if (json.bgColor) {
									$(this).css('background-color', json.bgColor);
								}
								if (json.color) {
									$(this).css('color', json.color);
								}
								if (json.isBold) {
									$(this).css('font-weight', 'bold');
								}
							}
						}
						num ++;
					});
				}

				showSpinning(false);

				try {
                    onNestTableRefresh_[(${nestFieldName})]();
                } catch (e) {};
            });
        }

		// 自动拉单
		var isAutoSel = [(${isAutoSel})];
		var pageType = '[(${pageType})]';
		if(isAutoSel) {
			// 如果是自动嵌套拉单，每隔两秒执行检查是否刷新表格
			var fields = '[(${mainFormFieldNames})]';
			console.log('isAutoSel fields', fields);
			var fieldNames = fields.split(",");

			var fieldObj = findObj(fieldNames[0]);
			var formObj = $(fieldObj).closest('form')[0];

			var oldValueArr = getFormValue(fieldNames, formObj);
			var ajaxData = {
				'flowId':'[(${flowId})]',
				'parentFormCode':'[(${parentFormCode})]',
				'parentId':'[(${mainId})]',
				'nestFieldName':'[(${nestFieldName})]',
				'isFirst':true
			};
			if (oldValueArr != null) {
				for (var i in fieldNames) {
					ajaxData[fieldNames[i]] = oldValueArr[i];
				}
			}

			// 如果是模块编辑，则不需要自动拉单，否则将只显示拉单结果，而无法显示原来的数据
			if ("edit" != pageType) {
				ajaxPost('/nestsheetctl/autoSel.do', ajaxData).then((data) => {
					console.log('data', data);
					if(data.ret == '1') {
						var newIds = data.newIds;
						if (newIds==null) {
							newIds = "";
						}
						var calcFields = data.calcFields;
						var rowCss = data.rowCss;

						// 需用setTimeout，以免此js与loadNestCtl未完成时无 refreshNestTableCtl 方法带来冲突
						// 另外，如果值太小了，也会导致因loadNestCtl未加完成，在自动拉单后重新生成嵌套表时，未能正常删除loadNestCtl生成的工具条，导致出现两个工具条，且标题列出现两个序号
						setTimeout("refreshNestTableCtl[(${nestFieldName})]('" + newIds + "', " + JSON.stringify(calcFields) + ", " + JSON.stringify(rowCss) + ")", 500);
					}
				});
			}

			if (fields != '') { // 配置了条件,没有配置条件则不处理
				var sint = window.setInterval(function() {
					// 重新获取获取的条件的值
					var newValueArr = getFormValue(fieldNames, formObj);
					// console.log('autoSel setInterval newValueArr', newValueArr, 'formObj', formObj, 'fieldNames', fieldNames);
					if (newValueArr != null) {
						if(JSON.stringify(oldValueArr) != JSON.stringify(newValueArr)) {
							// 判断新值数组中是否全为空，如果是，则不拉单，否则会导致保存后刷新时再次拉单冲掉了原来的记录
							var isNewAllEmpty = true;
							for (var k in newValueArr) {
								if (newValueArr[k] != '') {
									isNewAllEmpty = false;
								}
							}
							if (isNewAllEmpty) {
								return;
							}
							console.log('oldValueArr', JSON.stringify(oldValueArr));
							console.log('newValueArr', JSON.stringify(newValueArr));
							oldValueArr = newValueArr;
							var ajaxData = {
								'flowId':'[(${flowId})]',
								'parentFormCode':'[(${parentFormCode})]',
								'parentId':'[(${mainId})]',
								'nestFieldName':'[(${nestFieldName})]',
								'isFirst':false
							};
							for (var i in fieldNames) {
								ajaxData[fieldNames[i]] = newValueArr[i];
							}

							ajaxPost('/nestsheetctl/autoSel.do', ajaxData).then((data) => {
								console.log('data', data);
								if(data.ret == '1'){
									var newIds = data.newIds;
									if (newIds==null) {
										newIds = "";
									}
									var calcFields = data.calcFields;
									var rowCss = data.rowCss;
									console.log('ajaxPost newIds', newIds);
									// 需用setTimeout，以免此js与loadNestCtl未完成时无refreshNestTableCtl方法带来冲突
									setTimeout("refreshNestTableCtl[(${nestFieldName})]('" + newIds + "', " + JSON.stringify(calcFields) + ", " + JSON.stringify(rowCss) + ")", 500);
								}
							});
						}
					} else {
						window.clearInterval(sint);
					}
				},200);
				getCurFormUtil().addInterval(sint, '[(${formName})]');
			}
		}

		// 获取主表单中的值并拼接成sql的where字句
		function getFormValue(fieldNames, formObj) {
			var arr = new Array();
			for (var i = 0;i < fieldNames.length;i++) {
				var obj = findObjInFormObj(formObj, fieldNames[i]);
				// console.log('getFormValue obj', obj);
				if (obj) {
					arr[i] = obj.value;
				} else {
					// 可能为 curUserRole
					console.warn('getFormValue 表单中未找到: ' + fieldNames[i]);
					arr[i] = "";
				}
			}
			return arr;
		}
	[/]

	[# th:if="${op ne 'forRefresh'}"]
	function getCellIndex(cellName) {
		var r = '', c = '';
		for (var i = 0; i < cellName.length; i++) {
			if (!Number.isFinite(parseInt(cellName[i], 10))) {
				c += cellName[i];
			} else {
				break;
			}
		}
		// i -= 1;
		if (i < cellName.length) {
			for (; i < cellName.length; i++) {
				r += cellName[i];
			}
		}

		// 大写字母A到Z的ASCII码值是65到90
		c = c.toUpperCase().charCodeAt(0) - 65; // 从0开始
		r = parseInt(r) - 1; // 从0开始

		console.log('r', r, 'c', c);
		return [r, c];
	}

	function getCell(nestFieldName, cellName) {
		var arrIndex = getCellIndex(cellName);
		var r = arrIndex[0];
		var c = arrIndex[1];

		var colPrefixNum = 0;
		$('#nestTable_' + nestFieldName + ' tr:eq(' + (r+1) + ')').each(function() {
			if ($(this).find('.td-chk')) {
				colPrefixNum ++;
			}
			if ($(this).find('.td-no')) {
				colPrefixNum ++;
			}
		});
		c += colPrefixNum;
		// r += 1;

		var $cell = $('#nestTable_' + nestFieldName + ' tr:eq(' + r + ') td:eq(' + c + ')');
		var $obj = $cell.find('[name^=nest_field_]');
		var val = 0;
		if ($obj[0]) {
			val = parseFloat($obj.val());
		} else {
			console.warn(cellName + ' is not found');
		}
		console.log(cellName + '=' + val);
		return val;
	}

	function getCellSum(nestFieldName, cellBegin, cellEnd) {
		var arrIndexB = getCellIndex(cellBegin);
		var rb = arrIndexB[0];
		var cb = arrIndexB[1];

		var arrIndexE = getCellIndex(cellEnd);
		var re = arrIndexE[0];
		var ce = arrIndexE[1];

		var r = 0;
		// 同一列
		if (cb == ce) {
			cb = String.fromCharCode(65 + cb);
			console.log('cb', cb);
			for (var n = rb + 1; n <= re+1; n++) {
				r += getCell(nestFieldName, cb + n);
			}
		} else if (rb == re) {
			console.log('rb', rb);
			// 同一行
			for (var n = cb; n <= ce; n++) {
				r += getCell(nestFieldName, String.fromCharCode(65 + n) + (rb+1));
			}
		} else {
			console.error(cellBegin, cellEnd, '不是同一行，也不是同一列');
		}
		return r;
	}

	function callCalc(nestFieldName, inputObj) {
		var r = $(inputObj).attr('cellRow');
		var c = $(inputObj).attr('cellCol');

		// 更新对嵌套表的列进行sum操作的控件
		$("input[calc]").each(function() {
			var formula = $(this).attr('calc');
			if (formula.indexOf(c)==-1) {
				return;
			}
			if (!formula.indexOf(":") && formula.indexOf(r)==-1 && formula.indexOf(c)==-1) {
				return;
			}
			/*if (formula != '=SUM(E4:E9)-E5')
				return;*/

			console.log('formula', formula);
			var digit = $(this).attr('digit');
			var isRoundTo5 = $(this).attr('isRoundTo5');

			var arrCalc = getCalcSymbolsWithBracket(formula);
			console.log('calc', arrCalc);
			var that = this;

			for (var i in arrCalc) {
				if (!isOperator(arrCalc[i])) {
					var cell = arrCalc[i];
					var isSum = false;
					var regStr = /(sum\((.*?)\))/gi;
					var mactches = cell.match(regStr)
					var len = 0;
					if (mactches) {
						len = mactches.length;
						isSum = true;
					}
					if (isSum) {
						var params = RegExp.$2;
						var arrParam = params.split(":");
						var cellBegin = arrParam[0].trim();
						var cellEnd = arrParam[1].trim();
						arrCalc[i] = getCellSum(nestFieldName, cellBegin, cellEnd);
					} else {
						arrCalc[i] = getCell(nestFieldName, arrCalc[i]);
					}
				}
			}

			var formula = "";
			for (var i = 0; i < arrCalc.length; i++) {
				formula += arrCalc[i];
			}
			console.log('callCalc formula', formula);
			var calValue = 0;
			try {
				calValue = parseFloat(eval(formula));
			} catch (e) {
				console.warn('callCalc: ' + formula + ' is not valid');
			}
			if (!isNaN(calValue)) {
				$(that).val(calValue);
			} else {
				$(that).val('');
			}
		});
	}

	// 四则运算拆分算式
	function getCalcSymbolsWithBracket(str) {
		// 去除空格
		str = str.replaceAll(" ", "");
		if (str.indexOf("=") == 0)
			str = str.substring(1); // 去掉开头的=号
		var list = new Array();
		var curPos = 0;
		var prePos = 0;
		var k = 0;
		for (var i = 0; i < str.length; i++) {
			var s = str.charAt(i);
			if (s == '+' || s == '-' || s == '*' || s == '/' || s == '(' || s == ')') {
				if (prePos < curPos) {
					list[k] = str.substring(prePos, curPos).trim();
					k++;
				}
				list[k] = "" + s;
				k++;
				prePos = curPos + 1;
			}
			curPos++;
		}
		if (prePos <= str.length - 1)
			list[k] = str.substring(prePos).trim();

		// ['sum', '(', 'B1:B2', ')', '-', 'B1']
		// 将sum算式合并
		var ary = [];
		for (i = 0; i < list.length; i++) {
			if (list[i].toLowerCase() == 'sum') {
				var sumFormula = 'sum';
				k = i + 1;
				while (k < list.length) {
					sumFormula += list[k];
					if (list[k] == ')') {
						break;
					}
					k++;
				}
				i = k;
				ary.push(sumFormula);
			} else {
				ary.push(list[i]);
			}
		}
		return ary;
	}

	function callCalculateOnloadNestTable(nestTableId, nestFieldName) {
		// 更新对嵌套表的列进行sum操作的控件
		$("input[kind='CALCULATOR']").each(function() {
			if ($(this).attr('formula')) {
				// 如果计算控件绑定的不是nestFieldName则跳过（当表单中存在相同子表时通过计算控件的属性nestFieldName加以区分）
				var nestField = $(this).attr('nestFieldName');
				if (nestField && nestField!=nestFieldName)
					return;

				var formula = $(this).attr('formula');
				var formCode = $(this).attr('formCode');
				// console.log('formCode=' + formCode);
				var digit = $(this).attr('digit');
				var isRoundTo5 = $(this).attr('isRoundTo5');
				var isSum = false;
				var regStr = /(sum\(([\w|\.]+)\))/gi;
				var mactches = formula.match(regStr)
				if (mactches) {
					isSum = true;
				}

				if (isSum) {
				   // 累加列
				   var field = RegExp.$2;
				   console.log('isSum=' + isSum + ' nestTableId=' + nestTableId + ' field=' + field);
				   if (field.indexOf("nest.")==0) {
						var p = field.indexOf(".");
						// 取得列名
						field = field.substring(p+1);
						// console.log('callCalculateOnloadNestTable field', field);
						var sumField = $(this);
						var v = 0;
						// 遍历嵌套表格，对匹配到的列求和
						var isFoundInNestTable = false;
						var $nestTable;
						if (formCode != null && formCode != '') {
							$nestTable = $("[id='" + nestTableId + "'][formCode='" + formCode + "']");
						}
						else {
							$nestTable = $("[id='" + nestTableId + "']");
						}

						$nestTable.find("[name^='nest_field_" + nestFieldName + '_' + field + "']").each(function() {
							// 去掉后缀为_realshow的控件
							if ($(this).attr('id') && $(this).attr('id').lastIndexOf('_realshow')!=-1) {
								return;
							}
							isFoundInNestTable = true;
							var cellV = $(this).val();
							if (cellV == "") {
								return;
							}
							if (!isNaN(cellV)) {
								v += eval(cellV);
							}
						});

						// console.log("nestTableId=" + nestTableId + " formula=" + formula + " field=" + field + " v=" + v + " isFoundInNestTable=" + isFoundInNestTable);
						// 如果在对应的嵌套表中找到了算式中相应的字段
						if (isFoundInNestTable) {
							try  {
								if (isRoundTo5 != null && isRoundTo5 == 1){
									var digitNum = parseFloat(digit);
									if (!isNaN(digitNum)){
										v = v.toFixed(digitNum);
									}
								}
								else if(isRoundTo5 != null && isRoundTo5 == 0){
									var digitNum = parseFloat(digit);
									if (!isNaN(digitNum)) {
										v = v.toFixed(digitNum + 1);
										v = changeTwoDecimal_f(v, digitNum);
									}
								}
							}
							catch (e) {}
							sumField.val(v);
						}
						else {
							// 不能置为0，如果存在多个嵌套表格，有可能会把在其它嵌套表格中被算到的计算控件值给清0了
							// sumField.val(0);
						}
				   }
				}
			}
		});
	}

	function initEventOfNestTable(nestTableId, nestFieldName) {
		$("input[kind='CALCULATOR']").each(function() {
			if ($(this).attr('formula')) {
				// 如果计算控件绑定的不是nestFieldName则跳过（当表单中存在相同子表时通过计算控件的属性nestFieldName加以区分）
				var nestField = $(this).attr('nestFieldName');
				if (nestField && nestField!=nestFieldName)
					return;

				var formula = $(this).attr('formula');
				var formCode = $(this).attr('formCode');
				var digit = $(this).attr('digit');
				var isRoundTo5 = $(this).attr('isRoundTo5');

				var isSum = false;
				var regStr = /(sum\(([\w|\.]+)\))/gi;
				var mactches = formula.match(regStr)
				var len = 0;
				if (mactches) {
					len = mactches.length;
					isSum = true;
				}
				if (isSum) {
				   // 累加列
				   var field = RegExp.$2;
				   if (field.indexOf("nest.")==0) {
						var p = field.indexOf(".");
						// 取得字段名
						field = field.substring(p+1);

						// 遍历所有的嵌套表格，对匹配到的列绑定change事件
						if (formCode != null) {
							$("[id='" + nestTableId + "'][formCode='" + formCode + "']").each(function() {
								bindChangeEvent(nestTableId, $(this), field, nestFieldName);
							});
						}
						else {
							$("[id='" + nestTableId + "']").each(function() {
								bindChangeEvent(nestTableId, $(this), field, nestFieldName);
							});
						}
				   }
				}
			}
		});
	}

	function bindChangeEvent(nestTableId, $obj, field, nestFieldName) {
		console.log('bindChangeEvent', $obj[0], nestTableId, nestFieldName);
		$obj.find("[name^='nest_field_" + nestFieldName + "_" + field + "']").each(function() {
			var ctlField = this;
			var oldValue = $(ctlField).val();
			var sint = setInterval(function() {
				if (oldValue != $(ctlField).val()) {
					oldValue = $(ctlField).val();
					callCalculateOnloadNestTable(nestTableId, nestFieldName);
				}
			}, 200);
			getCurFormUtil().addInterval(sint, '[(${formName})]');
		});
	}

	function initNestTableCalculate(nestTableId, nestFieldName) {
		console.log("$(\"#nestTable_\"" + nestFieldName + ").attr('hasCalcFields')", $("#nestTable_" + nestFieldName).attr('hasCalcFields'));
		if($("#nestTable_" + nestFieldName).attr('hasCalcFields') == 1)
			return;

		// console.log("nestTableId=" + nestTableId);
		// 绑定change事件
		initEventOfNestTable(nestTableId, nestFieldName);
		// 执行计算
		callCalculateOnloadNestTable(nestTableId, nestFieldName);
	}

	function initTr(nestFieldName, $tr, rowId, isAdd) {
		$tr.find("input[kind='DATE']").each(function() {
			if ($(this).attr('readonly')==null) {
				try {
					$(this).datetimepicker({
						lang: 'ch',
						datepicker: true,
						timepicker: false,
						validateOnBlur: false,
						format: 'Y-m-d'
					});
				} catch (e) {
				}
			}
		});

		$tr.find("input[kind='DATE_TIME']").each(function() {
			if ($(this).attr('readonly')==null) {
				try {
					$(this).datetimepicker({
						lang: 'ch',
						datepicker: true,
						timepicker: true,
						validateOnBlur: false,
						format:'Y-m-d H:i:00'
					});
				} catch (e) {
				}
			}
		});

		if (isAdd) {
			// 将$nestTr中的控件的id、name值改为以nest_field_打头，以免与主表中的字段冲突
			$tr.find('input,select,textarea,span').each(function() {
				// 不改变行首的checkbox的name，并置其值为rowId，以便于在服务端根据rowId获取
				if ($(this).attr("name") == "chk" + nestFieldName) {
					$(this).val(rowId);
					return;
				}
				if ($(this).attr("name") == "rowId" + nestFieldName) {
					$(this).val(rowId);
					return;
				}

				var name = $(this).attr('name');
				if (typeof(name) != 'undefined') {
					// 如果名称为带有_realshow，则按规律转换
					var p = name.indexOf("_realshow");
					if (p!=-1) {
						var tmpL = name.substring(0, p);
						var tmpR = name.substring(p);
						var newName = 'nest_field_' + nestFieldName + '_' + tmpL + "_" + rowId + tmpR;
						// console.log("tmpL=" + tmpL + " tmpR=" + tmpR + " newName=" + newName);
						$(this).attr('name', newName);
					}
					else {
						var p = name.indexOf("_show");
						if (p!=-1) {
							var tmpL = name.substring(0, p);
							var tmpR = name.substring(p);
							var newName = 'nest_field_' + nestFieldName + '_' + tmpL + '_' + rowId + tmpR;
							$(this).attr('name', newName);
						}
						else {
							$(this).attr('name', 'nest_field_' + nestFieldName + '_' + name + "_" + rowId);
						}
					}
				}

				var id = $(this).attr('id');
				if (typeof(id) != 'undefined') {
					// 如果名称为带有_realshow，则按规律转换
					var p = id.indexOf("_realshow");
					if (p!=-1) {
						var tmpL = id.substring(0, p);
						var tmpR = id.substring(p);
						var newId = 'nest_field_' + nestFieldName + '_' + tmpL + '_' + rowId + tmpR;
						$(this).attr('id', newId);
					}
					else {
						var p = id.indexOf("_show");
						if (p!=-1) {
							var tmpL = id.substring(0, p);
							var tmpR = id.substring(p);
							var newId = 'nest_field_' + nestFieldName + '_' + tmpL + '_' + rowId + tmpR;
							$(this).attr('id', newId);
						}
						else {
							$(this).attr('id', 'nest_field_' + nestFieldName + '_' + id + '_' + rowId);
						}
					}
				}
			});

			// 绑定$tr中计算控件所关联字段的change事件
			$("input[kind='CALCULATOR']").each(function() {
				if ($(this).attr('formula')) {
					var formula = $(this).attr('formula');
					var formCode = $(this).attr('formCode');
					var digit = $(this).attr('digit');
					var isRoundTo5 = $(this).attr('isRoundTo5');

					var isSum = false;
					var regStr = /(sum\(([\w|\.]+)\))/gi;
					var mactches = formula.match(regStr)
					if (mactches) {
						isSum = true;
					}
					if (isSum) {
					   // 累加列
					   var field = RegExp.$2;
					   if (field.indexOf("nest.")==0) {
							var p = field.indexOf(".");
							// 取得字段名
							field = field.substring(p+1);

							var nestTableId = 'nestTable_' + nestFieldName;
							// 遍历所有的嵌套表格，对匹配到的列求和
							if (formCode != null) {
								$("[id='" + nestTableId + "'][formCode='" + formCode + "']").each(function() {
									bindChangeEvent(nestTableId, $tr, field, nestFieldName);
								});
							}
							else {
								$("[id='" + nestTableId + "']").each(function() {
									bindChangeEvent(nestTableId, $tr, field, nestFieldName);
								});
							}
					   }
					}
				}
			});
		}

		$tr.find('input,select,textarea').each(function() {
			// 重置nestTr中控件的宽度样式
			if ($(this).is("input") || $(this).is("textarea")) {
				var type = $(this).attr('type');
				if (type!=null) {
					if (type=='button' || type=='checkbox' || type=='radio') {
						return;
					}
				}
				// 忽略含有_realshow的元素
				if ($(this).attr('name')) {
					if ($(this).attr('name').indexOf("_realshow")==-1) {
						$(this).css('width', '96%');
					}
					else {
						$(this).css('width', '80%');
					}
				}
				else {
					$(this).css('width', '96%');
				}
			}
			else if ($(this).is("select")) {
				$(this).css('width', '99%');
			}

			if (
			  (this.type != 'hidden' &&
				this.type != 'checkbox' &&
				this.type != 'radio' &&
				this.type != 'button' &&
				this.tagName == 'INPUT') ||
			  this.tagName == 'SELECT' ||
			  this.tagName == 'TEXTAREA'
			) {
				$(this).addClass('ant-input-affix-wrapper');
				$(this)
					.focus(function () {
					  $(this).addClass('ant-input-affix-wrapper-focus');
					})
					.blur(function () {
					  $(this).removeClass('ant-input-affix-wrapper-focus');
					});
			}
		});

		$tr.find('input').each(function () {
			if ($(this).attr('kind') == 'DATE' || $(this).attr('kind') == 'DATE_TIME') {
			  $(this).attr('autocomplete', 'off');
			}
		});

		// 替换按钮的样式
		var btns = $tr[0].getElementsByTagName('button');
		for (var i = 0; i < btns.length; i++) {
			// 如果不是表单域选择宏控件的按钮
			if (!$(btns[i]).hasClass('btnSearch')) {
				btns[i].className = 'ant-btn ant-btn-primary ant-btn-sm';
			}
		}

		initCalculatorFieldNameOfFormula($tr, rowId, nestFieldName);
		initCalculatorInTr($tr);

		initFormulaCtl($tr, '[(${flowId})]', '[(${formName})]');
	}

	// 将行中的计算控件中的字段改为nest_field_***_rowid
	function initCalculatorFieldNameOfFormula($tr, rowId, nestFieldName) {
		$tr.find("input[kind='CALCULATOR']").each(function(){
			var calObj = $(this);
			var formula = $(this).attr('formula');
			if (formula != null) {
				if (formula.toLowerCase().indexOf("subdate") != -1 || formula.toLowerCase().indexOf("adddate") != -1){
					// 对日期绑定事件
					// 时间相减方法subdate(d1, d2)
					var pat = /subdate\(([a-z0-9_-]+),([a-z0-9_-]+)\)/ig;
					formula = formula.replace(pat, function(p1, date1, date2){
						var isSelect = false;
						date1 = 'nest_field_' + nestFieldName + '_' + date1 + '_' + rowId;
						date2 = 'nest_field_' + nestFieldName + '_' + date2 + '_' + rowId;
						return "subdate(" + date1 + "," + date2 + ")";
					});

					// 时间相加方法addDate(d1, d2)
					var pat = /adddate\(([a-z0-9_-]+),([0-9-]+)\)/ig;
					formula = formula.replace(pat, function(p1, date1, date2){
						var isSelect = false;
						date1 = 'nest_field_' + nestFieldName + '_' + date1 + '_' + rowId;
						date2 = 'nest_field_' + nestFieldName + '_' + date2 + '_' + rowId;
						return "adddate(" + date1 + "," + date2 + ")";
					});

					$(this).attr('formula', formula);
				}else{
					var ary = getSymbolsWithBracket(formula);
					for (var i=0; i < ary.length; i++) {
						// ary[i]可能为0.2这样的系数
						if (!isOperator(ary[i]) && !isNumeric(ary[i])) {
							if (o('nest_field_' + nestFieldName + '_' + ary[i] + '_' + rowId)) {
								ary[i] = 'nest_field_' + nestFieldName + '_' + ary[i] + '_' + rowId;
							}
						}
					}
					formula = "";
					for (var i=0; i < ary.length; i++) {
						formula += ary[i];
					}
					$(this).attr('formula', formula);
				}
			}
		});
	}

	// 初始化行中的计算控件
	function initCalculatorInTr($tr) {
		$tr.find("input[kind='CALCULATOR']").each(function() {
			var calObj = $(this);
			if ($(this).attr('formula')) {
				var formula = $(this).attr('formula');
				if (formula.toLowerCase().indexOf("subdate") != -1 || formula.toLowerCase().indexOf("adddate") != -1){
					// 对日期绑定事件
					formula = initFuncFieldEvent(formula, calObj);
				}else{
					var ary = getSymbolsWithBracket(formula);
					for (var i=0; i < ary.length; i++) {
						// ary[i]可能为0.2这样的系数
						if (!isOperator(ary[i]) && !isNumeric(ary[i])) {
							var isSelect = false;
							var obj = $("input[name='" + ary[i] + "']")[0];
							if(!obj) {
								obj = $("select[name='" + ary[i] + "']")[0];
								if (!obj) {
									// 因为字段可能为不可写状态，所以o可能为null，所以此处把提示注释掉，而且表单设计时是选择字段，所以字段名不会错
									// alert("计算控件" + calObj.attr("name") + "，算式" + formula + "中的字段：" + ary[i] + " 不存在！");
								}
								else {
									isSelect = true;
								}
							}
							if (obj) {
								bindEvent(obj, calObj, isSelect);
							}
						}
					}
				}
			}
		});

		$tr.find("input[kind='CALCULATOR']").each(function(){
			if ($(this).attr('formula')) {
				doCalculate($(this));
			}
		});
	}

	function initFormulaCtl($tr, flowId, formName) {
		$tr.find("input[isFormula='true']").each(function() {
			ajaxGetJS("/flow/macro/macroJsFormulaCtl?pageType=add"
			+ "&formCode=" + $(this).attr('formCode')
			+ "&fieldName=" + $(this).attr('name') + "&flowId=" + flowId + "&cwsFormName=" + formName + "&isHidden=" + $(this).attr('isHidden') + "&editable=" + $(this).attr('editable')
			, {});
		});
	}

	[/]
</script>
</body>
</html>